<?php

namespace App\Http\Controllers\API;

use App\Model\User\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Prophecy\Argument;
use App\Utils\TeacherRechargeUnit;

class APIController extends Controller
{
    public $url = 'http://8ae4db79.ngrok.io';

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        try {
            $data = $request->all();
            if (empty($data)) {
                return 'ceshi';
            }
            $signature = $data['signature'];
            $timestamp = $data['timestamp'];
            $nonce = $data['nonce'];
            $echostr = $data['echostr'];
            $token = "xxxx";  //请按照公众平台官网\基本配置中信息填写
            $list = [$token, $timestamp, $nonce];
            sort($list, SORT_STRING);
            $listStr = implode($list);
            $listStr = sha1($listStr);
            if ($listStr == $signature) {
                return $echostr;
            } else {
                return '';
            }


        } catch (\Exception $exception) {
            return Argument::any();
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        /*
         * 请求原始数据流
         * */
        $message = file_get_contents("php://input");
        if (!empty($message)) {
            $postObj = simplexml_load_string($message, 'SimpleXMLElement', LIBXML_NOCDATA);
            $reMsgType = $postObj->MsgType;
            $resultStr = '';
            switch ($reMsgType) {
                case "text":
                    $resultStr = $this->receiveText($postObj);
                    break;
                case "event":
                    $resultStr = $this->receiveEvent($postObj);
                    break;
            }
            return $resultStr;
        } else {
            echo "";
            exit;
        }
    }

    private function receiveText($object)
    {
        switch ($object->Content) {
            case "余额":
                $user_meal = User::where('weixin_id', $object->FromUserName)->with('meal_supplement_balance')->first();
                if (!empty($user_meal)) {
                    $contentStr = "当前余额为" . $user_meal['meal_supplement_balance']['meal_supplement_balance'];
                } else {
                    $contentStr[] = [
                        'Title' => '账户管理',
                        'Description' => '你目前没有绑定账号,请先绑定账号',
                        'PicUrl' => $this->url . '/img/logo.png',
                        'Url' => $this->url . '/binding?weixin_id='.$object->FromUserName,
                    ];
                }
                break;
        }
        if (is_array($contentStr)) {
            $resultStr = $this->transmitNews($object, $contentStr);
        } else {
            $resultStr = $this->transmitText($object, $contentStr);
        }
        return $resultStr;
    }

    private function receiveEvent($object)
    {
        switch ($object->Event) {
            case "subscribe":
                $content = "欢迎关注教职工餐补系统";
                break;
            case "unsubscribe":
                $content = "欢迎下次关注教职工餐补系统";
                break;
            case "scancode_waitmsg":
                $qr_data = $object->ScanCodeInfo->ScanResult;//接受微信的消息
                $qr_data = explode('=', $qr_data);
                $data[$qr_data[0]] = $qr_data[1];
                $teacher = User::where('weixin_id', $object->FromUserName)->whereHas('groups', function ($query) {
                    $query->where('group_id', 1);
                })->select('id')->first();
                if (!empty($teacher)) {
                    $data['order_price'] = $data['order_price'] * 0.9;
                    $deduction = TeacherRechargeUnit::deduction($data['order_price'], $teacher['id']);
                    if ($deduction['code'] == 403) {
                        $content = $deduction['data'];
                    } elseif ($deduction['code'] == 200) {
                        $content[] = [
                            'Title' => '消费金额',
                            'Description' => '消费金额: ' . $data['order_price'] . "\n" . "余额: " . $deduction['data'] . "\n",
                            'PicUrl' => $this->url . '/img/logo.png',
                            'Url' => $this->url . '/binding?weixin_id='.$object->FromUserName,
                        ];
                    } else {
                        $content = "服务器出现故障，请稍后再试";
                    }

                } else {
                    $user = User::where('weixin_id', $object->FromUserName)->select('id')->first();
                    if (empty($user)) {
                        $content[] = [
                            'Title' => '账户管理',
                            'Description' => '你目前没有绑定账号,请先绑定账号',
                            'PicUrl' => $this->url . '/img/logo.png',
                            'Url' => $this->url . '/binding?weixin_id='.$object->FromUserName,
                        ];
                    } else {
                        $deduction = TeacherRechargeUnit::deduction($qr_data['order_price'], $user['id']);
                        if ($deduction['code'] == 403) {
                            $content = $deduction['data'];
                        } elseif ($deduction['code'] == 200) {
                            $content[] = [
                                'Title' => '消费金额',
                                'Description' => '消费金额: ' . $qr_data['order_price'] . "\n" . "余额: " . $deduction['data'] . "\n",
                                'PicUrl' => $this->url . '/img/logo.png',
                                'Url' => $this->url . '/binding?weixin_id='.$object->FromUserName,
                            ];
                        } else {
                            $content = "服务器出现故障，请稍后再试";
                        }
                    }
                }
                break;
            case "CLICK":
                switch ($object->EventKey) {
                    case "rselfmenu_1_0" :
                        $content[] = [
                            'Title' => '账户管理',
                            'Description' => '账户管理',
                            'PicUrl' => $this->url . '/img/logo.png',
                            'Url' => $this->url . '/binding?weixin_id='.$object->FromUserName,
                        ];
                        break;
                    case "rselfmenu_1_1" :
                        $user_meal = User::where('weixin_id', $object->FromUserName)->with('meal_supplement_balance')->first();
                        if (!empty($user_meal)) {
                            $content = "当前余额为" . $user_meal['meal_supplement_balance']['meal_supplement_balance'];
                        } else {
                            $content[] = [
                                'Title' => '账户管理',
                                'Description' => '你目前没有绑定账号,请先绑定账号',
                                'PicUrl' => $this->url . '/img/logo.png',
                                'Url' => $this->url . '/binding?weixin_id='.$object->FromUserName,
                            ];
                        }
                        break;
                    default:
                        $content = '出现错误';
                        break;
                }
                break;
            default:
                $content = '出现错误';
                break;
        }
        if (is_array($content)) {
            $resultStr = $this->transmitNews($object, $content);
        } else {
            $resultStr = $this->transmitText($object, $content);
        }
        return $resultStr;
    }

    private function transmitText($object, $content)
    {
        $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            </xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), 'text', $content);
        return $resultStr;
    }

    private function transmitNews($object, $arr_item, $funcFlag = 0)
    {
        if (!is_array($arr_item)) return;
        $itemTpl = "<item>
                <Title><![CDATA[%s]]></Title>
                 <Description><![CDATA[%s]]></Description>
                 <PicUrl><![CDATA[%s]]></PicUrl>
                 <Url><![CDATA[%s]]></Url>
                    </item>";
        $item_str = "";
        foreach ($arr_item as $item)
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        $newsTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <Content><![CDATA[]]></Content>
                    <ArticleCount>%s</ArticleCount>
                    <Articles>$item_str</Articles>
                    <FuncFlag>%s</FuncFlag>
                    </xml>";
        $resultStr = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item), $funcFlag);
        return $resultStr;
    }


}
